package cn.mujiankeji.mbrowser.工具.操作

import cn.mujiankeji.mbrowser.数据.数据库.AppDatabase
import cn.mujiankeji.mbrowser.数据.数据库.DBIpv4
import cn.mujiankeji.mbrowser.数据.数据库.DBIpv6
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.koin.core.context.GlobalContext
import java.net.InetAddress
import java.net.UnknownHostException


/**
 * 处理IP入库
 */
object IPUtils {

    suspend fun 是否为中国大陆IP段(ip : String) : Boolean{
        val regex = Regex("([1-9][0-9]{0,2})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})")
        regex.find(ip).let { it ->
            if (it != null){
                // IPv4 地址处理
                if (it.groupValues.size == 5) {
                    val a = it.groupValues[1].toInt()
                    val b = it.groupValues[2].toInt()
                    val c = it.groupValues[3].toInt()
                    val d = it.groupValues[4].toInt()
                    
                    // 使用 Room 数据库查询
                    GlobalContext.get().getOrNull<AppDatabase>()?.let { db ->
                        val ipRanges = withContext(Dispatchers.IO) {
                            db.IPv4地址段().根据A段查询IPv4地址段2(a)
                        }
                        
                        // 检查每个 IP 范围
                        for (ipRange in ipRanges) {
                            if (eqddd(b, ipRange.b, ipRange.b2) && 
                                eqddd(c, ipRange.c, ipRange.c2) && 
                                eqddd(d, ipRange.d, ipRange.d2)) {
                                return true
                            }
                        }
                    }
                }
            }
            else {
                // IPv6 地址处理
                val ipParts = ip.split(":")
                if (ipParts.size in 3..8){
                    val v1 = if (ipParts.size > 0) ipParts[0] else ""
                    val v2 = if (ipParts.size > 1) ipParts[1] else ""
                    val v3 = if (ipParts.size > 2) ipParts[2] else ""
                    val v4 = if (ipParts.size > 3) ipParts[3] else ""
                    
                    // 使用 Room 数据库查询
                    GlobalContext.get().getOrNull<AppDatabase>()?.let { db ->
                        withContext(Dispatchers.IO) {
                            // 按照不同精度查询
                            // 精确匹配 v1+v2+v3+v4
                            if (v4.isNotEmpty()) {
                                val count = db.IPv6地址段().根据完整前缀查询IPv6地址段数量(v1, v2, v3, v4, 4)
                                if (count > 0) return@withContext true
                            }
                            
                            // 匹配 v1+v2+v3
                            if (v3.isNotEmpty()) {
                                val count = db.IPv6地址段().根据三段前缀查询IPv6地址段数量(v1, v2, v3, 3)
                                if (count > 0) return@withContext true
                            }
                            
                            // 匹配 v1+v2
                            if (v2.isNotEmpty()) {
                                val count = db.IPv6地址段().根据两段前缀查询IPv6地址段数量(v1, v2, 2)
                                if (count > 0) return@withContext true
                            }
                            
                            // 匹配 v1
                            if (v1.isNotEmpty()) {
                                val count = db.IPv6地址段().根据一段前缀查询IPv6地址段数量(v1, 1)
                                if (count > 0) return@withContext true
                            }
                            
                            false
                        }
                    }
                }
            }
        }
        return false
    }
    
    private fun eqddd(a : Int, b : Int, b2 : Int): Boolean {
        if (a == b) return true
        if (b2 == 0) return false
        return a in b..b2
    }

    // 解析IP段 103.66.200.0/22
    fun parserIP(ipz : String) : DBIpv4? {
        try {
            val regex = Regex("([1-9][0-9]{0,2})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d+)")
            regex.find(ipz)?.let {
                val ipv4 = DBIpv4()
                if (it.groupValues.size == 6){
                    ipv4.def = ipz
                    ipv4.a = it.groupValues[1].toInt()
                    ipv4.b = it.groupValues[2].toInt()
                    ipv4.c = it.groupValues[3].toInt()
                    ipv4.d = it.groupValues[4].toInt()
                    ipv4.zd = it.groupValues[5].toInt()

                    // 8,8,8,8
                    if (ipv4.zd > 24){
                        ipv4.d2 = pmaxz(ipv4.d, ipv4.zd - 24)
                    }
                    else if (ipv4.zd > 16){
                        ipv4.c2 = pmaxz(ipv4.c, ipv4.zd - 16)
                        ipv4.d2 = 255
                    }
                    else if (ipv4.zd > 8){
                        ipv4.b2 = pmaxz(ipv4.b, ipv4.zd - 8)
                        ipv4.c2 = 255
                        ipv4.d2 = 255
                    }
                    else{
                        // 有一个整顿的吗？ 不存在
                        return null
                    }

                    return ipv4
                }
            }
        }catch (e : Exception){
            e.printStackTrace()
        }
        return null
    }

    private fun pmaxz(v : Int, size : Int) : Int {
        var bb = ""
        for (i in 0 until (8 - size)) {
            bb += "1"
        }
        if (bb.isEmpty()) return 0

        // 剩余的转为加数
        return v + bb.toInt(2)
    }

    /**
     * 域名取IP地址
     */
    suspend fun getIP(域名 : String) : String? {
        if (!域名.startsWith("http")) return null
        try {
            val addresses = withContext(Dispatchers.IO) {
                InetAddress.getAllByName(域名)
            }
            for (address in addresses) {
                val ipAddress = address.hostAddress
                return ipAddress
                // println()
            }
        } catch (e: UnknownHostException) {
            e.printStackTrace()
        }
        return null
    }
}